package lab1;
import java.util.AbstractList;
/**
 * ArrayList with efficient add and get.
 * Null values are not allowed  
 * @author Julia
 *
 */


public class MyArrayList extends AbstractList<Integer>{
	
	private Integer[] array;
	private int capacity; 
	private int size; 	
	
	/**
	 * Create an empty list with initial capacity of ten.
	 */
	
	public MyArrayList(){
		size=0;
		capacity=10;
		array=new Integer[capacity];	
	}
	
	/**
	 * Return the number of elements in this list
	 * 
	 * @return the number of elements in this list
	 */
	
	@Override
	public int size() {
		return size;
	}
	
	/**
	 * Append element to the end of this list
	 * 
	 * @param el Element to be appended to this list
	 * @return true
	 * @throws NullPointerException
	 */
	
	public boolean add(Integer el) {
		if (el==null){
			throw new NullPointerException("Element can't be NULL");
		}
		ensureCapacity(size+1);
		array[size++]=el;		
		return true;
	}
	
	/**
	 * Return the element at the position in this list
	 * 
	 * @param ind Index of the element to return
	 * @return the element at the position in this list
	 * @throws IndexOutOfBoundsException
	 */
	
	@Override	
	public Integer get(int ind) {		
		if (ind<0||ind>=size){
			throw new IndexOutOfBoundsException("Wrong index: "+ind);
		}
		return array[ind];
	}
	
	/**
	 * Remove the element at the position in this list
	 * 
	 * @param ind Index of the element to return
	 * @return the element that was removed from this list
	 * @throws IndexOutOfBoundsException
	 */
	
	public Integer remove(int ind){
		if (ind<0||ind>=size){
			throw new IndexOutOfBoundsException("Wrong index: "+ind);
		}
		Integer el=array[ind];
		int CountMoved=size-ind-1;
		if (CountMoved>0){
			System.arraycopy(array, ind+1, array, ind, CountMoved);
		}
		size--;		
		return el;
	}
	
	/**
	 * Remove the first occurrence of the element from this list
	 * 
	 * @param el Element to be removed from this list
	 * @return true if element was removed from list
	 */
	
	public boolean removeEl(Integer el){
		if(el==null){
			throw new NullPointerException("Element can't be NULL");
		}
		for (int i=0; i<size; i++){
			if (el.equals(array[i])){
				remove (i);
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Remove all elements from this list.
	 */
	
	public void clear(){
		size=0;
		capacity=10;
		array=new Integer[capacity];
	}		
	
	/**
	 * Increase the capacity of this list, if it is necessary
	 * @param capacity1 Minimum capacity
	 */
	
	private void ensureCapacity(int capacity1){
		if (capacity>=capacity1){
			return;			
		}
		Integer[] array1=new Integer[2*capacity];
		System.arraycopy(array, 0, array1, 0, capacity);
		array=array1;
		capacity=2*capacity;	
	}
	
	
}
